import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:hixing_app/views/coordinate_painter/coordinate_utils.dart';

/// 坐标系画板

class CoordinatePainterPage extends StatefulWidget {
  const CoordinatePainterPage({super.key});

  @override
  CoordinatePainterPageState createState() => CoordinatePainterPageState();
}

class CoordinatePainterPageState extends State<CoordinatePainterPage>
    with SingleTickerProviderStateMixin {
  /// late变量初始化为空。不能直接.. repaet
  late AnimationController paintCtrl = AnimationController(
    duration: const Duration(milliseconds: 2000),
    vsync: this,
  );

  @override
  void initState() {
    super.initState();
    paintCtrl.forward();
  }

  @override
  void dispose() {
    paintCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('坐标画板'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (paintCtrl.value != null)
                Container(
                  child: CustomPaint(
                    size: Size(300, 300),
                    painter: CoordinatePainter(patinCtrl: paintCtrl),
                  ),
                ),
            ],
          ),
        ));
  }
}

class CoordinatePainter extends CustomPainter {
  CoordinatePainter({required this.patinCtrl}) : super(repaint: patinCtrl);
  final Animation<double> patinCtrl;
  CoordinateUtils? coordinate;

  @override
  void paint(Canvas canvas, Size size) {
    coordinate ??= CoordinateUtils(
      size: size,
      color: Colors.red,
    );

    print(size);

    /// 把原点移到左下角
    canvas.translate(0.0, size.height);
    Paint paint = Paint();

    int hLineNum = 10;
    int vLineNum = 10;
    int gapNum = 10;
    coordinate!.paintCoordinate(
        canvas: canvas, hLineNum: hLineNum, vLineNum: vLineNum, gapNum: gapNum);

    /// 绘制点
    var offsetList = [
      Offset(
        13,
        15,
      ),
      Offset(
        50,
        10,
      ),
      Offset(
        10,
        30,
      ),
      Offset(
        60,
        80,
      ),
      Offset(
        70,
        30,
      ),
      Offset(
        90,
        80,
      ),
    ];

    /// 计算出当前坐标系的比例，然后把把offset的坐标转换到实际画板的size的坐标，就可以实现正确绘制点位了
    var scaleX = size.width / (hLineNum * gapNum);
    var scaleY = size.height / (vLineNum * gapNum);

    /// 按 dx 属性排序
    offsetList.sort((a, b) => a.dx.compareTo(b.dx));

    /// 把点位用scale转换到实际画板的坐标
    var transferOffset = offsetList
        .map((item) => Offset(item.dx, -item.dy).scale(scaleX, scaleY))
        .toList();

    /// 绘制点
    canvas.drawPoints(
        PointMode.points,
        transferOffset,
        paint
          ..color = Colors.red
          ..strokeWidth = 8
          ..strokeCap = StrokeCap.round);

    /// 点位转path
    Offset p1 = transferOffset[0];
    Path path = Path()..moveTo(p1.dx, p1.dy);
    for (var i = 1; i < transferOffset.length; i++) {
      path.lineTo(transferOffset[i].dx, transferOffset[i].dy);
    }

    /// 获取path路径参数
    PathMetrics pms = path.computeMetrics();

    /// 绘制path测量数据的列表
    pms.forEach((pm) {
      canvas.drawPath(
          pm.extractPath(0, pm.length * patinCtrl.value),
          paint
            ..style = PaintingStyle.stroke
            ..strokeWidth = 1.0);
    });
  }

  @override
  bool shouldRepaint(covariant CoordinatePainter oldDelegate) {
    return false;
  }
}
